import { Application } from "../Application";
import { miscCfg, RpcMsgId, sessCoder } from "../util/defines";
import { Session } from "./Session";

/**
 * 后端会话,可以看做前端会话的复制
 */
export class BackendSession extends Session {

    constructor(app: Application, sessBuf: Uint8Array) {
        let { uid, sid, setting } = sessCoder.decode(sessBuf);
        super(app, sid);
        this.uid = uid;
        this.setting = setting;
    }

    send(msgId: number, msg?: any) {
        return this.app.rpcService.send(this.sid, RpcMsgId.msgSend, { uid: this.uid, data: miscCfg.msgCoder.encode(msgId, msg) });
    }

    sends(msgs: { msgId: number; msg?: any; }[]) {
        let datas: Uint8Array[] = [];
        for (let msg of msgs) {
            datas.push(miscCfg.msgCoder.encode(msg.msgId, msg.msg));
        }
        return this.app.rpcService.send(this.sid, RpcMsgId.msgSend, { uid: this.uid, datas });
    }

    /**
     * 同步设置到前端服务器
     */
    syncSetting(setting = this.setting, deleteKeys?: string[]) {
        return this.app.rpcService.send(this.sid, RpcMsgId.syncSetting, { uid: this.uid, setting, deleteKeys });
    }

}